package com.llkj.contractmanagement.contractmanagement.login;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.llkj.contractmanagement.main.BaseActivity;
import com.llkj.contractmanagement.main.MainActivity;
import com.llkj.contractmanagement.R;
import com.llkj.contractmanagement.http.HttpMethod;
import com.llkj.contractmanagement.http.UrlConfig;
import com.llkj.contractmanagement.model.LoginBean;
import com.llkj.contractmanagement.model.UserInfoBean;
import com.llkj.contractmanagement.utils.GsonUtil;
import com.llkj.contractmanagement.utils.Md5Utils;
import com.llkj.contractmanagement.utils.ToastUtil;

import java.util.HashMap;
import java.util.Set;

import butterknife.Bind;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * author: dong.yj
 * created on: 2016/8/15 17:12
 * description:登录界面
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.et_un)
    EditText etUn;
    @Bind(R.id.et_pw)
    EditText etPw;
    @Bind(R.id.cb_argment)
    CheckBox cbArgment;
    @Bind(R.id.cb_remenber_pw)
    CheckBox cbRemeberPw;//记住密码
    @Bind(R.id.btn_login)
    Button btnLogin;
    @Bind(R.id.tv_user_agree)
    TextView tvUserAgreement;
    private String un = "";//账号
    private String pw = "";//密码
    private SharedPreferences sp;
    private static final int MSG_SET_ALIAS = 1001;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        init();
        //获得实例对象
        sp = this.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        //判断记住密码多选框的状态
        if (sp.getBoolean("ISCHECK", false)) {
            //设置默认是记录密码状态
            cbRemeberPw.setChecked(true);
            etUn.setText(sp.getString("USER_NAME", ""));
            etPw.setText(sp.getString("PASSWORD", ""));
        }
    }

    private void init() {
        initData();
        setListenter();
    }

    private void initData() {


    }

    private void setListenter() {
        btnLogin.setOnClickListener(this);
        tvUserAgreement.setOnClickListener(this);
        cbRemeberPw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (cbRemeberPw.isChecked()) {
                    sp.edit().putBoolean("ISCHECK", true).commit();

                } else {
                    sp.edit().putBoolean("ISCHECK", false).commit();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.btn_login:
                login();
//                intent = new Intent(this, MainActivity.class);
//                startActivity(intent);
                break;
            case R.id.tv_user_agree:
                intent = new Intent(LoginActivity.this, UserAgreementActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void login() {
        un = etUn.getText().toString().trim();
        pw = etPw.getText().toString().trim();
        if (TextUtils.isEmpty(un)) {
            ToastUtil.makeShortText(LoginActivity.this, getString(R.string.please_input_un));
            return;
        }
        if (TextUtils.isEmpty(pw)) {
            ToastUtil.makeShortText(LoginActivity.this, getString(R.string.please_input_pw));
            return;
        }
        if (!cbArgment.isChecked()) {
            ToastUtil.makeShortText(LoginActivity.this, "请阅读并同意用户协议");
            return;
        }
//        account	1	string	用户账号
//        password	1	string	密码
        HashMap<String, String> map = new HashMap<>();
        map.put("account", un);
        map.put("password", pw);
        HttpMethod.doLogin(this, this, map, UrlConfig.HTTP_DOLOGIN);
    }

    @Override
    public void onSuccessHttp(String responseInfo, int resultCode) {
        super.onSuccessHttp(responseInfo, resultCode);
        if (resultCode == UrlConfig.HTTP_DOLOGIN) {
            LoginBean loginBean = GsonUtil.GsonToBean(responseInfo, LoginBean.class);
            if (loginBean != null) {
                //登录成功和记住密码框为选中状态才保存用户信息
                if (cbRemeberPw.isChecked()) {
                    //记住用户名、密码、
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("USER_NAME", un);
                    editor.putString("PASSWORD", pw);
                    editor.commit();
                }
                String up = Md5Utils.string2MD5(un + pw);
                UserInfoBean userInfoBean = UserInfoBean.getInstance();
                userInfoBean.setAccess(loginBean);
                ToastUtil.makeShortText(this, "登录成功");
                startActivity(new Intent(this, MainActivity.class));
                this.finish();
                if (up.equals(loginBean.getPwd())) {
                    Intent intent = new Intent(this, EditPassWordActivity.class);
                    intent.putExtra("type", 0);
                    startActivity(intent);
                }
                if (!userInfoBean.isSetAlias()) {
                    mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, loginBean.getId()));
                }
                if (JPushInterface.isPushStopped(this)) {
                    JPushInterface.resumePush(this);
                }
            }
        }
    }

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    JPushInterface.setAlias(getApplicationContext(), (String) msg.obj, mAliasCallback);
                    break;
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            switch (code) {
                case 0://设置成功
                    UserInfoBean.getInstance().setSetAlias(true);
                    break;
                case 6002://设置失败
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
            }
        }
    };
}
